
# -*- coding: utf-8 -*-

# 拼多多关键词上传
from base_config import *
from manage.helper import  Helper
import  pymysql, requests
from multiprocessing import Process,Pool

from threading import Thread
db = pymysql.connect(**config)
cursor = db.cursor(pymysql.cursors.DictCursor)


class KeywordCase( object ):

    def __init__(self):

        pass


    def selectKeyword(self,id,db,cursor):

        str=''
        if id == 0:
            str= 'and (id%10=1 or id%10=0) '
        elif id == 1:
            str = 'and (id%10=2 or id%10=3) '
        elif id == 2:
            str = 'and (id%10=4 or id%10=5) '
        elif id == 3:
            str = 'and (id%10=6 or id%10=7) '
        else:
            str = 'and (id%10=8 or id%10=9) '
        # 随机选择一条数据
        Random_SQL = 'SELECT * FROM `keyword` WHERE status = 0 '+str+'  limit 1'


        # Random_SQL = 'SELECT * FROM keyword WHERE `status` = 0 ORDER BY RAND() LIMIT 1'

        # 随机选取
        cursor.execute( Random_SQL )

        result = cursor.fetchone()

        # 执行更新
        self.execStatus(result['id'],db,cursor)

        #数据上传

        self.apiRequest( result,db,cursor)

        return result


        # print( result )


    # 任务执行中
    def execStatus(self,id,db,cursor):

        # 执行更新语句
        EXEC_SQL = "UPDATE keyword SET status = 1 WHERE id ={0}"

        # 执行更新
        cursor.execute(EXEC_SQL.format(id))

        db.commit()

    # 任务完成
    def finishStatus(self,id,db,cursor):

        FINISH_SQL =  "UPDATE keyword SET status = 2 WHERE id ={0}"

        cursor.execute( FINISH_SQL.format(id) )

        db.commit()

    # 任务失败

    def failStatus(self, id,db,cursor):

        FINISH_SQL = "UPDATE keyword SET status = 3 WHERE id ={0}"

        cursor.execute(FINISH_SQL.format(id))

        db.commit()



    # 上传数据
    def apiRequest(self,name,db,cursor):


        # 生成签名

        sign = Helper.genSign(name['name'])

        data = {

            "keywords": name['name'],
            "source": "9999",
            "sign": sign

        }

        r = requests.post( domain_url['domain']['test_keyword_url'] ,data=data)

        print( r.text)

        if r.status_code == 200 and r.json()['code'] == 0:

            self.finishStatus( name['id'],db,cursor)

            print('上传成功:',name['name'])

        else:

            self.failStatus( name['id'],db,cursor)

            print('上传失败:',name['name'])


    def main(self,id,db,cursor):

        while True:

            result= self.selectKeyword(id,db,cursor)

            if result == None:

                quit()


if __name__ == '__main__':



    key = KeywordCase()

    # key.main()


    # pool = Pool(5)
    #
    # for i in range(5):
    #
    #     pool.apply_async(key.main,args=(i,))
    #
    # pool.close()
    # pool.join()

    # 线程中创建数据库
    db = pymysql.connect(**config)
    cursor = db.cursor(pymysql.cursors.DictCursor)

    process = []

    for i in range(10):



        p = Thread(target=key.main,args=(i,db,cursor)).start()

        process.append( p )


    for p in process:

        p.join()











    #
    # for i in range(5):
    #
    #     p = pool.apply_async(k.main,args=())
    #
    # pool.close()
    #
    # pool.join()
    #
    #
    #
    # pool = Pool(10)



















